import { getStorage, jump, setStorage, getCurrentPage } from "./utils"
import api from "../config/api";

let Qqmapwx = require('./qqmap-wx-jssdk.min.js')
/**
 * 退出登录
 * @param {boolean} modal 是否显示弹窗
 * @param {string} msg 退出登录信息
 */
export function logout(modal, msg) {
  const app = getApp()
  if (app.globalData.isFail) {
    return
  }
  app.globalData.isFail = true
  app.clearLogin()
  if (modal) {
    wx.showModal({
      content: msg || '登录失效,请重新登录',
      showCancel: false,
      success: function () {
        app.globalData.isFail = false
        jump('mine')
      }
    })
  } else {
    app.globalData.isFail = false
  }
}

/**
 * 用户权限拒绝
 * @param {*} callback 回调函数
 * @param {*} isFirst 是否是第一次
 */
export function userPermissionsDenied(callback, isFirst) {
  wx.showToast({
    title: isFirst ? '拒绝授权' : '授权失败',
    icon: 'none'
  })
  callback?.(null)
}

/**
 * 用户权限通过
 * @param {*} data 权限数据
 * @param {*} authName 权限名称
 * @param {*} callback 回调函数
 * @param {*} extra 额外参数
 */
export function userPermissionsPass(data, authName, callback, extra) {
  // 设置地理位置
  if (authName === 'userLocation') {
    setUserLocation(callback)
    return
  }
  // 设置摄像头权限
  if (authName === 'camera') {
    setUserCamera(callback)
    return
  }
  // 设置录音权限
  if (authName === 'record') {
    if (data.authSetting['scope.record']) {
      setUserRecord(callback)
    }
    return
  }
  // 设置保存到相册权限
  if (authName === 'writePhotosAlbum') {
    setUserWrite(callback, extra)
    return
  }
  callback?.(data)
}

/**
 * 获取用户权限
 * @param {*} authName 权限名称 userInfo: 用户信息 userLocation: 地理位置 userLocationBackground: 后台定位 werun: 微信运动步数 record: 录音功能 writePhotosAlbum: 保存到相册 camera: 摄像头
 * @param {*} callback 回调函数
 * @param {*} extra 额外参数
 */
export function getUserPermissions(authName, callback, extra) {
  // 权限列表
  const authMap = {
    userInfo: '用户信息',
    userLocation: '地理位置',
    userLocationBackground: '后台定位',
    werun: '微信运动步数',
    record: '录音功能',
    writePhotosAlbum: '相册',
    camera: '摄像头',
  }
  if (!authName || !authMap[authName]) {
    wx.showToast({
      title: '权限名称错误！',
      icon: 'none'
    })
    return
  }
  // 权限scope名称
  const scopeName = `scope.${authName}`
  wx.getSetting({
    success: (res) => {
      console.log('用户权限信息', res)
      // 已拒绝授权
      if (res.authSetting[scopeName] === false) {
        wx.showModal({
          title: '温馨提示',
          content: `可见分类需要获取你的${authMap[authName]}权限，请确认授权`,
          success: (res) => {
            console.log('用户权限弹窗确认信息', res)
            if (res.confirm) {
              wx.openSetting({
                success: (authRes) => {
                  console.log('用户权限页面信息', authRes)
                  // 已授权
                  if (authRes.authSetting[scopeName]) {
                    userPermissionsPass(authRes, authName, callback, extra)
                  } else {
                    userPermissionsDenied(callback)
                  }
                },
                fail: () => {
                  userPermissionsDenied(callback)
                }
              })
            } else {
              userPermissionsDenied(callback)
            }
          },
          fail: () => {
            userPermissionsDenied(callback)
          }
        })
        return
      }
      // 第一次授权
      if (!res.authSetting[scopeName]) {
        userPermissionsPass(res, authName, callback, extra)
      }
      // 已授权
      if (res.authSetting[scopeName]) {
        userPermissionsPass(res, authName, callback, extra)
      }
    },
    fail: () => {
      userPermissionsDenied(callback)
    }
  })
}

/**
 * 设置用户经纬度
 * @param {*} callback 回调函数
 */
export function setUserLocation(callback) {
  wx.getLocation({
    type: 'gcj02',
    success: (res) => {
      setStorage('latitude', res?.latitude || '')
      setStorage('longitude', res?.longitude || '')
      // 地理位置sdk
      let addressInfo = res
      let qqmapsdk = new Qqmapwx({
        key: '4NLBZ-BCSCU-27IVS-2DBBT-BCII3-FFBSZ'
      })
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: res?.latitude,
          longitude: res?.longitude
        },
        success: function (subRes) {
          const { address_component = {},ad_info = {} } = subRes.result
          const { province, city, district, street_number } = address_component;
          const { adcode } = ad_info;
          addressInfo.province = province
          addressInfo.city = city
          addressInfo.direct = district
          addressInfo.region = province + city + district
          addressInfo.fromAddr = street_number
          addressInfo.adcode = adcode
          setStorage("addressInfo", addressInfo)
          callback?.(addressInfo)
        },
        fail: function (res) {

        },
        complete: function (res) {

        }
      });
    },
    fail: () => {
      setStorage('latitude', '')
      setStorage('longitude', '')
      setStorage('addressInfo', {})
      userPermissionsDenied(callback, true)
    },
  })
}

// 获取用户经纬度
export function getUserLocation() {
  const latitude = getStorage('latitude')
  const longitude = getStorage('longitude')

  if (latitude && longitude) {
    return [latitude, longitude]
  }

  return null
}
//选择地理位置
export function chooseLocation(callback, address) {
  let qqmapsdk = new Qqmapwx({
    key: '4NLBZ-BCSCU-27IVS-2DBBT-BCII3-FFBSZ'
  })
  wx.chooseLocation({
    ...((address?.latitude && address?.longitude ? {
      latitude: address.latitude,
      longitude: address.longitude,
    } : {})),
    success: function (res) {
      const { latitude, longitude } = res;
      qqmapsdk.reverseGeocoder({
        location: {
          latitude,
          longitude
        },
        success: function (subRes) {
          const { address_component = {} } = subRes.result
          const { province, city, district, street_number } = address_component;
          const addressInfo = {
            province: province,
            city: city,
            direct: district,
            region: province + city + district,
            fromAddr: street_number,
            latitude,
            longitude
          }
          if (callback) {
            callback(addressInfo);
          }
        }
      })
    },
    fail: function () {
      wx.getSetting({
        success: function (res) {
          var statu = res.authSetting;
          if (!statu['scope.userLocation']) {
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
              success: function (tip) {
                if (tip.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] === true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        //授权成功之后，再调用chooseLocation选择地方
                        wx.chooseLocation({
                          success: function (res) {
                            const { latitude, longitude } = res;
                            qqmapsdk.reverseGeocoder({
                              location: {
                                latitude,
                                longitude
                              },
                              success: function (subRes) {
                                const { address_component = {} } = subRes.result
                                const { province, city, district, street_number } = address_component;
                                const addressInfo = {
                                  province: province,
                                  city: city,
                                  direct: district,
                                  region: province + city + district,
                                  fromAddr: street_number,
                                  latitude,
                                  longitude
                                }
                                if (callback) {
                                  callback(addressInfo);
                                }
                              }
                            }
                            )
                          },
                        })
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'success',
                          duration: 1000
                        })
                      }
                    },
                    fail: () => {
                      if (callback) {
                        callback({});
                      }
                    }
                  })
                }
              }
            })
          }
        },
        fail: function (res) {
          if (callback) {
            callback();
          }
          wx.showToast({
            title: '调用授权窗口失败',
            icon: 'success',
            duration: 1000
          })
        }
      })
    }
  })
}

/**
 * 设置用户本地写入权限
 * @param {*} callback 回调函数
 * @param {*} extra 额外参数
 */
export function setUserWrite(callback, extra) {
  wx.saveImageToPhotosAlbum({
    filePath: extra?.filePath,
    success: (res) => {
      setStorage('write', res || 1)
      callback?.(res)
    },
    fail: () => {
      setStorage('write', '')
      userPermissionsDenied(callback, true)
    }
  })
}

// 获取用户本地写入权限
export function getUserWrite() {
  return !!getStorage('write')
}

/**
 * 设置用户摄像头权限
 * @param {*} callback 回调函数
 */
export function setUserCamera(callback) {
  setStorage('camera', 1)
  callback?.(true)
}

// 获取用户摄像头权限
export function getUserCamera() {
  return !!getStorage('camera')
}

/**
 * 设置用户录音权限
 * @param {*} callback 回调函数
 */
export function setUserRecord(callback) {
  setStorage('record', 1)
  callback?.(true)
}

// 获取用户录音权限
export function getUserRecord() {
  return !!getStorage('record')
}

/*
 * 根据坐标获取距离
 * @param {string} location 坐标 lat,lng;lat,lng…
 * @param {*} callback 回调函数
 */
export function getDistanceByLocation(location, callback) {
  const qqmapsdk = new Qqmapwx({
    key: '4NLBZ-BCSCU-27IVS-2DBBT-BCII3-FFBSZ'
  })
  const latitude = getStorage('latitude')
  const longitude = getStorage('longitude')
  if (latitude && longitude && location) {
    qqmapsdk.calculateDistance({
      form: { latitude, longitude },
      to: location,
      mode: 'straight',
      success: (res) => {
        callback?.(res.result.elements)
      },
    })
  }
}

/**
 * 获取分享配置
 * @param {String} type 页面场景
 * @param {Object} event 分享按钮事件 from：button按钮 menu 菜单 shareType: 1分享好友 2分享朋友圈 target：dataset数据 
 * @param {string} title 分享标题
 * @param {string} path 分享路径 || 传参
 * @param {string} imageUrl 分享图片
 */
export function shareOptions(type, event, title, path, imageUrl) {
 console.log('分享参数：',type, event, title, path, imageUrl)
 const userId = getStorage('userId') || ''
 let url = getCurrentPage() //当前页面url
 let shareCategory = event.from === 'button'? 2 : 1
 let shareType = event?.shareType === 2? 2 : 1
 // 保存分享记录
 const app = getApp()
 if (app?.globalData) {
   app.globalData.shareCategory = shareCategory
   app.globalData.shareType = shareType
 }
 if(app.isLogin()){
  let params = {
    platform: 1, //1：小程序
    shareCategory, //分享类型 1：微信菜单 2：自有分享按钮
	  shareType, //分享方式 1：分享给朋友 2：分享到朋友圈
	  url
  }
    wx.request({
      url: api.addPageShare,
      data: params,
      method: 'POST',
      header: {
        'content-type': "application/json",
         token: getStorage("token")
      }
    })
 }
  /** 分享朋友圈 */
  if(event?.shareType === 2){
    return {
      title,
      query: path,
      imageUrl
    } 
  }
  /** 分享好友 */
  // 答题
  if (type === 'test') {
    return {
      title: '全国垃圾分类答题测试',
      path: '/pages/test/test?inviteData=' + userId,
      imageUrl: 'https://image-classify.daieco.com/kejian-second/HgymZSZQ8Fb9397f7a2f73de297785fa250e70ec36ac.png'
    }
  }
  // 邀请
  if (type === 'invite') {
    return {
      title: '垃圾袋免费派发中，点击领取',
      path: `/pages/index/index?invite_user_id=${userId}&inviteData=${userId}`,
      imageUrl: 'https://image-classify.daieco.com/kejian-quanzi/wHn6Cdq5bpMqb2d79a11762ddd0f1edeb50dca204311.png'
    }
  }
  // 新邀请
  if(type === 'newInvite'){
    return {
      title: '和我一起养成垃圾分类好习惯',
      path: `/pages/inviteFriends/inviteFriends?new_invite_user_id=${userId}`,
      imageUrl: 'https://image-classify.daieco.com/kejian-quanzi/jPqeBiUylOVBf3a2f19b53e25daca37d49ce974370cb.png'
    }
  }
  // 闲置
  if(type === 'idle'){
    return {
      title: '家门口的闲置免费互送平台',
      path: `/pages/idleHome/idleHome?inviteData=${userId}`,
      imageUrl: ''
    }
  }
  // 25天活动、抽奖活动
  if(type === 'award'){
    return {
      title: '点击参与垃圾分类，领千元家电大奖',
      path: `/pages/openScreen/openScreen?inviteData=${userId}&share=1`,
      imageUrl: 'https://image-classify.daieco.com/kejian-second/EOF8YA9G2SCk181811e706888fb7d41413ac8bd338f1.png'
    }
  }
  // 用户奖励
  if(type === 'userAward'){
    return {
      title: '垃圾袋免费派发中，点击领取',
      path: `/pages/userAward/userAward?invite_user_id=${userId}&inviteData=${userId}`,
      imageUrl: 'https://image-classify.daieco.com/kejian-second/S7w0HpJTQq8xffc4952cbd9cd5b16b5ec0863e5c733e.png'
    }
  }
  // 邀请好友领鸡蛋
  if(type === 'inviteWechatFriend'){
    return {
      title: '和我一起分类拍照，免费拿鸡蛋',
      path: `/pages/openScreen/openScreen?inviteData=${userId}&share=2&shareUserId=${userId}&activityId=${2}`,
      imageUrl: 'https://image-classify.daieco.com/kejian-quanzi/OmXPN7C89Rnx52d947ac431fb38bbf23dc8701e1f71a.png'
    }
  }
  // 帖子分享
  if (type === 'post') {
    const { picUrls, content, shareType, me } = event?.target?.dataset?.item || {}
    return {
      title: ((shareType !== 1 && me) ? content : null) || (shareType === 1 ? '你的好友邀请你一起参加“为垃圾分类，给城市减负“，点击加入！' : '我在圈子上发现了新内容，快来看看'),
      imageUrl: (!shareType ? picUrls?.[0] : null) || 'https://image-classify.daieco.com/kejian-second/6fNj79Ro2j4J3542ce8ecec14a26143f3b6e328a54e5.png',
      path: '/pages/index/index?inviteData=' + userId,
    }
  }
  // 助力活动
  if(type === 'helpActivity'){
    return {
      title,
      path,
      imageUrl
    }
  }
  // 默认 type：default
  if(type === 'default'){
   return {
    title: title? title : '你的好友邀请你一起参加“为垃圾分类，给城市减负“，点击加入！',
    path: path? path : '/pages/index/index?inviteData=' + userId,
    imageUrl: imageUrl === null? '' : imageUrl? imageUrl : 'https://image-classify.daieco.com/kejian-second/6fNj79Ro2j4J3542ce8ecec14a26143f3b6e328a54e5.png'
   }
  }
  // 系统默认 type：other
  return {}
}
